<template>
    <div class="app-container calendar-list-container">
        <div class="filter-container">
            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="编码名称" v-model="listQuery.AcCode">
            </el-input>
            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="公司名称" v-model="listQuery.AcName">
            </el-input>

            <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
            <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="edit">添加</el-button>
            <el-button class="filter-item" type="primary" icon="document" @click="handleDownload">导出</el-button>
        </div>

        <el-table :key='tableKey' :data="list" v-loading.body="listLoading" border fit highlight-current-row style="width: 100%">

            <el-table-column align="center" label="序号" width="65">
                <template scope="scope">
                    <span>{{scope.row.Id}}</span>
                </template>
            </el-table-column>

            <el-table-column width="100px" label="公司编码">
                <template scope="scope">
                    <span>{{scope.row.AcCode}}</span>
                </template>
            </el-table-column>

            <el-table-column min-width="300px" label="公司名称">
                <template scope="scope">
                    <span>{{scope.row.AcName}}</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="操作" width="150">
                <template scope="scope">
                    <el-button v-if="scope.row.status!='published'" size="small" type="success" @click="handleModifyStatus(scope.row,'published')">修改
                    </el-button>
                    <el-button v-if="scope.row.status!='deleted'" size="small" type="danger" @click="handleDelete(scope.row.Id)">删除
                    </el-button>
                </template>
            </el-table-column>

        </el-table>

        <div v-show="!listLoading" class="pagination-container">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page"
                           :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form class="small-space" :model="postData" :rules="rules" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
                <el-form-item label="公司编码">
                    <el-input v-model="postData.AcCode"></el-input>
                </el-form-item>

                <el-form-item label="公司名称">
                    <el-input v-model="postData.AcName"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align: center;">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button v-if="dialogStatus=='create'" type="primary" @click="create">确 定</el-button>
                <el-button v-else type="primary" @click="update">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import { fetchList, fetchPv } from 'api/article_table';
    import { parseTime } from 'utils';
    import { getList, postData, delData} from 'api/company';
    import { validateURL } from 'utils/validate';
    export default {
        name: 'table_demo',
        data() {
            const validateRequire = (rule, value, callback) => {
                if (value === '') {
                    this.$message({
                        message: rule.field + '为必传项',
                        type: 'error'
                    });
                    callback(null)
                } else {
                    callback()
                }
            };
            return {
                list: null,
                total: null,
                listLoading: true,
                listQuery: {
                    page: 1,
                    limit: 20,
                    Id: '',
                    AcCode: undefined,
                    AcName: undefined,
                    AcUpdate: undefined,
                },
                postData: {
                    AcCode: '',
                    AcName: ''
                },
                importanceOptions: [1, 2, 3],
                statusOptions: ['published', 'deleted'],
                dialogFormVisible: false,
                dialogStatus: '',
                textMap: {
                    update: '编辑',
                    create: '创建'
                },
                tableKey: 0,
                rules: {
                    AcCode: [{ validator: validateRequire }],
                    AcName: [{ validator: validateRequire }]
                }

            }
        },
        created() {
            this.getList();
        },
        filters: {
            statusFilter(status) {
                const statusMap = {
                    published: 'success',
                    deleted: 'danger'
                };
                return statusMap[status]
            },
            typeFilter(type) {
                return calendarTypeKeyValue[type]
            }
        },
        methods: {
            getList() {
                this.listLoading = false;
                getList().then(response => {
                    this.list = response.data;
                    this.total = response.data.total;
                    this.listLoading = false;
                }).catch(err => {
                    this.fetchSuccess = false;
                    console.log(err);
                })
            },
            handleFilter() {
                this.getList();
            },
            handleSizeChange(val) {
                this.listQuery.limit = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.listQuery.page = val;
                this.getList();
            },
            handleModifyStatus(row, status) {
                this.$message({
                    message: '操作成功',
                    type: 'success'
                });
                row.status = status;
            },
            handleCreate() {
                $(".el-dialog--small").css("width", "30%");
                this.dialogStatus = 'create';
                this.dialogFormVisible = true;
            },
            handleUpdate(row) {
                this.temp = Object.assign({}, row);
                this.dialogStatus = 'update';
                this.dialogFormVisible = true;
            },
            handleDelete(row) {
                delData(row).then(function(response){
                    console.log(response);
                    location.reload()
                    this.$notify({
                        title: '成功',
                        message: '删除成功',
                        type: 'success',
                        duration: 2000
                    });
                }).catch(err => {
                    this.fetchSuccess = false;
                    console.log(err);
                })
            },
            create() {
                if (this.postData.AcCode.length === 0 || this.postData.AcName.length === 0) {
                    this.$notify({
                        title: '提交错误',
                        message: '请填写完成字段',
                        type: 'warning'
                    });
                }else{
                    postData(this.postData).then(function(response){
                        console.log(response);
                        this.$message({
                            message: '提交成功',
                            type: 'success'
                        });
                        this.listLoading = false;
                    }).catch(err => {
                        this.fetchSuccess = false;
                        console.log(err);
                    })
                }
            },
            update() {
                this.postData.timestamp = new Date();
                for (const v of this.list) {
                    if (v.id === this.postData.id) {
                        const index = this.list.indexOf(v);
                        this.list.splice(index, 1, this.postData);
                        break;
                    }
                }
                this.dialogFormVisible = false;
                this.$notify({
                    title: '成功',
                    message: '更新成功',
                    type: 'success',
                    duration: 2000
                });
            },
            handleDownload() {
                require.ensure([], () => {
                    const { export_json_to_excel } = require('vendor/Export2Excel');
                    const tHeader = ['时间', '地区', '类型', '标题', '重要性'];
                    const filterVal = ['AcUpdate', 'province', 'AcCode'];
                    const data = this.formatJson(filterVal, this.list);
                    export_json_to_excel(tHeader, data, 'table数据');
                })
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                    if (j === 'AcUpdate') {
                        return parseTime(v[j])
                    } else {
                        return v[j]
                    }
                }))
            }
        }
    }
</script>
